<template>
	<view class="mem-all-box">
		<view class="search-box">
			<u-search placeholder="搜索" v-model="keyword" height="72" shape="square" searchIconSize="36"
				:showAction="false" @search="searchVal" @change="$u.debounce(searchVal, 300)"></u-search>
		</view>
		<view class="memorandum-book-wp" v-if="list.length">
			<view class="mem-box">
				<u-swipe-action  autoClose>
					<u-swipe-action-item v-for="(item,index) in list" :key="item.id" :options="options1" @click.stop="deleteMem(item,index)" :name="item.id" autoClose>
						<view class="swipe-action" @click="toMemInfo(item,index)">
							<view class="swipe-action__content">
								<view class="swipe-action__content__text">{{item.title}}</view>
								<view class="swipe-action__content__sub_text">{{item.createTime}}</view>
							</view>
						</view>
					</u-swipe-action-item>
				</u-swipe-action>

			</view>
		</view>
		<view class="empty" v-if="!list.length && firstLoad">
			<u-empty mode="data" icon="https://file.casugn.com/storecompcard/temp/空页面@2x(1)_1681113483838.png"
				iconSize="240rpx" text="暂无备忘录" textSize="28rpx">
			</u-empty>
		</view>
		<cus-add-btn :safeAreaInsetBottom="false" @click="add"></cus-add-btn>
	</view>

</template>

<script>
	import {
		mapState
	} from 'vuex'
	export default {
		data() {
			return {
				keyword: '',
				options1: [{
					text: '删除',
					style: {
						backgroundColor: '#e45656'
					}
				}],
				is_authorization: false,
				appid: 'wxed485786e1dbee9b',
				secret: "",
				openId: '',
				list: [],
				id: '',
				openId: '',
				title: '',
				pageNo: 1,
				pageSize: 10,
				total: 0,
				accessToken: "",
				titleValue: '',
				firstLoad: false

			};
		},
		onShow() {
			this.openId = uni.getStorageSync('openId').openid
			this.list = []
			this.queryMemLists(1)
			// this.queryAccessToken()
		},
		onReachBottom() {
			if ((this.list.length === this.total) && this.firstLoad) {
				return uni.showToast({
					title: '已全部加载',
					icon: 'none'
				})
			}
			this.queryMemLists()
		},
		// onUnload() {
		// 	uni.$off('save')
		// },
		methods: {
			searchVal(val) {
				this.queryMemLists(1)
			},
			queryAccessToken() {
				this.$api.getAccessToken().then(res => {
					console.log("获取AccessToken")
					console.log(res)
					if (res.success) {
						this.accessToken = res.result.access_token
					}
				})
			},
			queryMemLists(rest) {
				this.pageNo = rest ? 1 : ++this.pageNo
				let data = {
					id: this.id,
					openId: this.openId,
					title: `*${this.keyword}*`,
					pageNo: this.pageNo,
					pageSize: this.pageSize
				}
				uni.showLoading({
					title: '加载中'
				})
				this.$api.getMemLists(data).then(res => {
					console.log(res)
					if (res.success) {
						let arr = res.result.records
						arr.forEach(item => {
							item.content = item.descn
						})
						this.list = this.pageNo == 1 ? arr : this.list.concat(arr)
						this.total = res.result.total
					}
				}).finally(() => {
					this.firstLoad = true
					setTimeout(() => {
						uni.hideLoading()
					}, 700)
				})
			},
			deleteMem(item, index) {
				console.log(item)
				this.$api.deleteMemById(item.id).then(res => {
					console.log(res)
					if (res.success) {
						uni.showToast({
							title: res.result
						})
						this.queryMemLists(1)
					}
				})
			},
			toMemInfo(item, index) {
				console.log(item, index)
				uni.navigateTo({
					url: '/pagesCard/memorandumInfo/memorandumInfo?item=' + encodeURIComponent(JSON.stringify(
						item))
				})
			},
			add() {
				uni.navigateTo({
					url: '/pagesCard/memorandumInfo/memorandumInfo?addType=1'
				})
				let id = (this.list.length + 1).toString()
				// uni.$on('save', res => { //开启监听保存事件
				// 	let content = res.html
				// 	let idx = this.list.findIndex(m => m.id === id)
				// 	if (idx !== -1) {
				// 		this.$set(this.list[idx], 'content', content)
				// 	} else {
				// 		this.list.push({
				// 			id: id,
				// 			title: '文章' + id,
				// 			content
				// 		})
				// 	}
				// })
			},
			sendMessage() {
				let self = this
				//下方的thing1，thing2和其他，对应的是你选取模板的模板详情中的字段名称(可在小程序后台模板查看对应的字段，要和上面的字段一样)，需要更改成你自己的
				const pushmsg = {
					"touser": self.openId,
					"template_id": "YiTE88xGBTyvczEC8vt9rtXYsKz7ZZSSjI7wHvSrRCw",
					"data": {
						"thing1": {
							"value": "备忘录标题"
						},
						"thing2": {
							"value": "备忘录地点"
						},
						"time3": {
							"value": "18:50"
						}
					}
				}
				uni.request({
					// 此处的mytoken
					url: 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=' + this
						.accessToken,
					data: JSON.stringify(pushmsg),
					method: 'POST',
					success: function(res) {
						console.log(res);
					}
				})

			},

			// 开启订阅消息设置窗口
			openMsg() {
				var that = this;
				// 获取用户的当前设置，判断是否点击了“总是保持以上，不在询问”
				wx.getSetting({
					withSubscriptions: true, //是否获取用户订阅消息的订阅状态，默认false不返回
					success(res) {
						console.log("订阅消息的订阅状态", res);
						if (that.is_authorization) {
							uni.showToast({
								title: "您已订阅商机消息提醒，无需重复订阅！",
								icon: "none"
							});
						} else {
							if (res.subscriptionsSetting['YiTE88xGBTyvczEC8vt9rtXYsKz7ZZSSjI7wHvSrRCw'] ==
								"reject") { //用户点击了“总是保持以上，不再询问”
								wx.showModal({
									title: '温馨提示',
									content: "检测到您没有开启订阅消息的权限，是否去设置？",
									success: function(modal) {
										if (modal.confirm) { // 点击肯定
											wx.openSetting({
												withSubscriptions: true
											});
											that.is_authorization = true;
											uni.setStorageSync('is_authorization', true);
										} else {
											uni.showToast({
												title: "您已拒绝订阅消息授权，无法预约领取",
												icon: "error"
											});
											that.is_authorization = false;
										}
									}
								})
							} else { // 用户没有点击“总是保持以上，不再询问”则每次都会调起订阅消息
								// var templateid = that.setting.templateid.map(item => item.tempid)；
								let tmpid = ['YiTE88xGBTyvczEC8vt9rtXYsKz7ZZSSjI7wHvSrRCw'];
								uni.requestSubscribeMessage({
									tmplIds: tmpid,
									success(res) {
										if (res[tmpid[0]] == "accept") {
											uni.showToast({
												title: "订阅成功",
												icon: "none"
											});
											that.is_authorization = true;
											uni.setStorageSync('is_authorization', true);
										} else {
											uni.showToast({
												title: "您拒绝订阅消息授权，无法预约领取",
												icon: "none"
											});
											that.is_authorization = false;
										}
									},
									fail: (res) => {
										wx.showModal({
											title: '温馨提示',
											content: "检测到您没有开启订阅消息的权限，是否去设置？",
											success: function(modal) {
												if (modal.confirm) { // 点击肯定
													wx.openSetting({
														withSubscriptions: true
													});
													that.is_authorization = true;
													uni.setStorageSync('is_authorization',
														true);
												} else {
													uni.showToast({
														title: "您已拒绝订阅消息授权，无法预约领取",
														icon: "error"
													});
													that.is_authorization = false;
												}
											}
										})
									}
								})
							}
						}

					}
				})
			},
		}
	}
</script>
<style>
	page {
		height: 100%;
		background-color: #F7F8FA;
	}
</style>
<style lang="scss" scoped>
	.mem-all-box {
		padding-bottom: calc(20rpx + env(safe-area-inset-bottom));

		view {
			box-sizing: border-box;
		}

		.search-box {
			width: 100%;
			padding: 20rpx 32rpx;
			margin: 0 auto;
			background-color: #fff;
			position: sticky;
			top: 0;
			z-index: 20;
		}

		.memorandum-book-wp {
			border-radius: 20upx;
			width: 100%;
			padding-bottom: 40rpx;

			.mem-box {
				width: 100%;
				padding: 0 32rpx;
				background-color: #fff;

				.u-page {
					padding: 0;
				}

				.u-demo-block__title {
					padding: 10upx 0 2upx 15upx;
				}

				.swipe-action {
					&__content {
						padding: 25upx 0;

						&:active {
							opacity: .7;
						}

						&__text {
							font-size: 30upx;
							color: $u-main-color;
							// padding-left: 30rpx;
						}
					}
				}

				.swipe-action__content__text {
					overflow: hidden;
					text-overflow: ellipsis;
					white-space: nowrap;
					font-weight: bold;
					font-size: 32rpx;
					width: 660rpx;
					margin-bottom: 16rpx;
				}

				.swipe-action__content__sub_text {
					margin-top: 10upx;
					font-size: 26upx;
					color: #a6a6a6;
					overflow: hidden;
					text-overflow: ellipsis;
					white-space: nowrap;
					// width: 2em;  //用px单位亦可行
				}
			}

		}

		.empty {
			padding-top: 240rpx;
		}
	}
</style>